package com.polaris.live.widget.match_botton

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst.FREE_MATCH_LONG_3
import com.polaris.live.common.constant.PagConst.FREE_MATCH_PHONE
import com.polaris.live.common.constant.PagConst.START_MATCH_LONG_3
import com.polaris.live.common.event.MatchingAssetEvent
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.WidgetMatchBottonBinding
import com.polaris.live.net.homeService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.go_resp.MatchStartBean
import com.polaris.live.translation.R.string
import com.polaris.live.ui.main.activity.MainActivity
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.libpag.PAGScaleMode
import java.lang.ref.WeakReference

/**
 * free match 和 start matching 控件
 *
 * @author Created by 半仙 on 2023/10/25/025 15:05
 */
class MatchBottomView(context: Context, attributeSet: AttributeSet) : RelativeLayout(context, attributeSet) {

    private val mBinding = WidgetMatchBottonBinding.inflate(LayoutInflater.from(context), this, true)

    private lateinit var mViewModel: BaseViewModel

    private var mPage: Int = UserConst.From.UNKNOWN
    private var mLastPage: Int = UserConst.LastFrom.UNKNOWN

    //是否已经有性别了
    private var mIsHavaSex = false
    fun setViewModel(mViewModel: BaseViewModel) {
        this.mViewModel = mViewModel
    }

    fun setPage(page: Int) {
        this.mPage = page
    }

    private var fragmentReference: WeakReference<Fragment>? = null
    fun setFragment(fragment: Fragment) {
        fragmentReference = WeakReference(fragment)
    }

    private var activityReference: WeakReference<Activity>? = null
    fun setActivity(activity: Activity) {
        activityReference = WeakReference(activity)
    }

    fun setLastPage(lastPage: Int) {
        this.mLastPage = lastPage
    }

    init {
        if (UserManager.getUser().sex != AppConst.UserSex.NONE) {
            mIsHavaSex = true
        }
        anewView()
    }

    fun anewView(callAsset: Boolean? = null) {

        val asset = callAsset ?: (UserManager.getUser().call?.callAsset == true)
        val isFreeMatch =
            UserManager.getUser().sex == AppConst.UserSex.NONE || CommonUtils.isMan(UserManager.getUser().sex) && asset

        mBinding.pagGreenView.visibility = GONE
        mBinding.pagRedView.visibility = GONE

        if (isFreeMatch) {
            //Free Match
            showFreeMatch()
            mBinding.pagGreenView.visibility = VISIBLE
        } else if (CommonUtils.isMan(UserManager.getUser().sex)) {
            //Start Match
            showStartMatch()
            mBinding.pagRedView.visibility = VISIBLE
        } else if (UserManager.getUser().flag?.auditStatus == CommonConst.FLagState.AUDIT) {
            //Start Match
            showStartMatch()
            mBinding.pagRedView.visibility = VISIBLE
            mBinding.llBottom.visibility = View.GONE
        } else {
            // Match and Live Streaming
            showMatchAndLiveStreaming()
            mBinding.pagRedView.visibility = VISIBLE
        }

        mBinding.pagGreenView.apply {
            path = FREE_MATCH_LONG_3
            setScaleMode(PAGScaleMode.Zoom)
            setRepeatCount(-1)
            play()
        }

        mBinding.pagRedView.apply {
            path = START_MATCH_LONG_3
            setScaleMode(PAGScaleMode.Zoom)
            setRepeatCount(-1)
            play()
        }
        mBinding.consBig.setOnSingleClickListener {
            if (onStartClick != null) {
                onStartClick?.invoke()
                return@setOnSingleClickListener
            }
            val context = context
            GlobalPopupManager.showCompletePopup(context) {
                if (activityReference?.get() is MainActivity && !mIsHavaSex) {
                    (activityReference?.get() as MainActivity).clearFragment()
                }
                //如果是男生点击 进入匹配
                if (CommonUtils.isMan(UserManager.getUser().sex)) {
                    mViewModel.requestLoading({
                        homeService.matchStart(MatchStartBean(CommonConst.MatchStart.MANUAL, mPage))
                    }, {
                        Router.builder(RoutePath.LIVE_MATCH_ACTIVIYT)
                            .withInt("page", mPage)
                            .withInt("lastPage", mLastPage)
                            .withLong("id", it.id)
                            .navigation()
                    }, {
                        ToastGravity.showGravity(it.errorMsg)
                    })
                } else {
                    //如果是女点击则判断有没有封面照 如果没有则进入封面照页面  如果有封面则开启直播坐等
                    if (context is LifecycleOwner) {
                        StartLiveProxy.builder(context, context)
                            .startLive(mViewModel, LiveConst.Type.LIVE_AND_MATCH)
                    }
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showStartMatch() {
        mBinding.pagPhone.visibility = View.GONE
        mBinding.tvMatch.text = "${StringUtils.getString(string.start_match)} "
        mBinding.tvMatch.setTextColor(ColorUtils.getColor(R.color.white))
        mBinding.llBottom.visibility = View.VISIBLE
    }

    @SuppressLint("SetTextI18n")
    private fun showFreeMatch() {
        mBinding.tvMatch.text = "${StringUtils.getString(string.free_match)} "
        mBinding.tvMatch.setTextColor(ColorUtils.getColor(R.color.color_127c00))
        mBinding.llBottom.visibility = View.GONE
        mBinding.pagPhone.apply {
            visibility = View.VISIBLE
            path = FREE_MATCH_PHONE
            setScaleMode(PAGScaleMode.Zoom)
            setRepeatCount(-1)
            play()
        }
    }

    private fun showMatchAndLiveStreaming() {
        mBinding.pagPhone.visibility = View.GONE
        mBinding.llBottom.visibility = View.GONE
        mBinding.tvMatch.text = StringUtils.getString(string.match_and_livestrearming)
        mBinding.tvMatch.setTextColor(ColorUtils.getColor(R.color.white))
    }

    private var onStartClick: (() -> Unit)? = null
    fun setOnStartClick(click: () -> Unit) {
        onStartClick = click
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        EventBus.getDefault().register(this)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MatchingAssetEvent) {
        anewView(event.callAsset)
    }
}